package com.mobileares.midp.widgets.client.tab;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: Tom
 * Date: 2011-3-29
 * Time: 14:26:05
 * To change this template use File | Settings | File Templates.
 */
public class TabPanel extends Composite implements ITab {
    private FlowPanel bar;
    private SimplePanel content;
    private int selected = -1;
    private Map<Integer, Widget> cache = new HashMap<Integer, Widget>();

    public TabPanel() {
        FlowPanel container = new FlowPanel();
        container.setStyleName("tab-tab");
        bar = new FlowPanel();
        bar.setStyleName("bar");
        container.add(bar);
        content = new SimplePanel();
        content.setStyleName("content");
        container.add(content);
        initWidget(container);
    }


    public Integer addTabItem(String text) {
        final Label item = new Label(text);
        item.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                SelectionEvent.fire(TabPanel.this, bar.getWidgetCount());
                setSelected(bar.getWidgetIndex(item));
            }
        });
        item.setStyleName("item");
        bar.add(item);
        return bar.getWidgetCount() - 1;
    }

    public void addItem(String text, Widget widget) {
        cache.put(addTabItem(text), widget);
    }

    public void setSelected(int selected) {
        if (this.selected != -1) {
            Widget widget = bar.getWidget(this.selected);
            widget.removeStyleName("selected");
        }
        bar.getWidget(selected).addStyleName("selected");
        this.selected = selected;
        content.setWidget(getItem(selected));
    }

    public Widget getItem(int index) {
        return cache.get(index);
    }

    /**
     * Adds a {@link com.google.gwt.event.logical.shared.SelectionEvent} handler.
     *
     * @param handler the handler
     * @return the registration for the event
     */
    public HandlerRegistration addSelectionHandler(SelectionHandler<Integer> handler) {
        return addHandler(handler, SelectionEvent.getType());
    }
}
